/*
 * Main UI class for MyLatexEditor v1.0
 * Includes methods and variables for application user interface
 */

/*
 * myLatexEdiotr.java
 *
 * Created on 22.Mar.2009, 21:51:51
 */
package com.meraklisina.latexeditor;

import com.meraklisina.latexeditor.mdi.Common.CommonGuiListener;
import com.meraklisina.latexeditor.mdi.Common.Tools;
import com.meraklisina.latexeditor.mdi.DialogActions.ActionOpen;
import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;
import com.meraklisina.latexeditor.toolbarCustomize.CustomizeForm;
import com.meraklisina.latexeditor.TemplateForm;
import com.meraklisina.latexeditor.AutoComplete;
import com.meraklisina.latexeditor.wizard.DynamicToolbarWizard;
import com.sun.pdfview.PDFFile;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

import java.awt.SystemTray;
import java.net.URI;


import org.w3c.dom.*;

/**
 *
 * @author kursattopcu
 */
public class BlueLatexEditor extends javax.swing.JFrame {
	
	public static BlueLatexEditor _BlueLatexEditorIns ;
	
	Tools CommonTool = new Tools();
	
    private static String currentFileName;
    private static String tempPdfFileName = "temp";
    private final static String tempStatic = "temp";
    private int tempCounter = 0;
    private PDFFile pdffile = null;
    private int LastPageDisplayed = 1;
    private int DocNumberOfPages = 0;
    private String latexExe = "latex";
    private String pdflatexExe = "pdflatex";
    private String dvipsExe = "dvips";
    static String _miktexPath;
    static String _language;
    public static boolean _onTheFlyCompilation;
    static String _operatingSystem = System.getProperty("os.name");
    
    
    /** Creates new form myLatexEdiotr */
    public BlueLatexEditor() {
        initComponents();
        try {
			CommonGuiListener.initListeners();
		} catch (Exception e) {
			e.printStackTrace();
		}
        createToolbarBtn.setVisible(false);
        java.lang.Thread autoSaveThread=new java.lang.Thread(new AutoSaveThread(this));
        autoSaveThread.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

    	// IT : For OS independency
    	if(!_operatingSystem.equals("Linux"))
    	{
	        latexExe += ".exe";
	        pdflatexExe += ".exe";
	        dvipsExe += ".exe";
    	}

		try {
			CreateConfigFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		LoadSettings();
    	lang.LoadLanguage(_language);
		SysTray();
		
        toolbarContextMenu = new javax.swing.JPopupMenu();
        customizeMenuItem = new javax.swing.JMenuItem();
        customizeDialog = new JDialog(this);
        customizeDialog.setModal(true);
        customizeDialog.setSize(430,300);
        customizeDialog.setResizable(false);
        customizeDialog.setTitle("Customize Toolbars");
        
        templateDialog = new JDialog(this);
        templateDialog.setModal(true);
        templateDialog.setSize(430,300);
        templateDialog.setResizable(false);
        templateDialog.setTitle("Template Creator Wizard");
        
        toolbarPanel = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        jToolBar2 = new javax.swing.JToolBar();
        newButton = new javax.swing.JButton();
        openButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        boldButton = new javax.swing.JButton();
        italicButton = new javax.swing.JButton();
        footNoteButton = new javax.swing.JButton();
        hrefButton = new javax.swing.JButton();
        underlineButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        alignLeftButton = new javax.swing.JButton();
        alignCenterButton = new javax.swing.JButton();
        alignRightButton = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        cutButton = new javax.swing.JButton();
        copyButton = new javax.swing.JButton();
        pasteButton = new javax.swing.JButton();
        jSeparator6 = new javax.swing.JToolBar.Separator();
        commentOutBtn = new javax.swing.JButton();
        commentInBtn = new javax.swing.JButton();
        createToolbarBtn = new javax.swing.JButton();
        jSeparator7 = new javax.swing.JToolBar.Separator();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxCovertTo = new javax.swing.JComboBox();
        jComboBoxSections = new javax.swing.JComboBox();
        convertToPdfButton = new javax.swing.JButton();
        hiddenLabel = new javax.swing.JLabel();
        btnPreview = new javax.swing.JButton();
        btnPreviewSelected = new javax.swing.JButton();
        prevButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        pagesTextField = new javax.swing.JTextField();
        jSplitPane1 = new ExtendedSplitPane();
        jSplitPane1.setDividerLocation(0.7);
        previewPanel1 = new com.meraklisina.latexeditor.PreviewPanel();
        jPanel1 = new javax.swing.JPanel();
        tab_Editors = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        outputTextArea = new javax.swing.JTextArea();
        outputLabel = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        fileMenuExitItem = new javax.swing.JMenu();
        fileMenuNewItem = new javax.swing.JMenuItem();
        fileMenuOpen = new javax.swing.JMenuItem();
        fileMenuSave = new javax.swing.JMenuItem();
        fileMenuSaveAs = new javax.swing.JMenuItem();
        fileMenuImport = new javax.swing.JMenuItem();
        fileMenuExport = new javax.swing.JMenuItem();
        fileMenuCloseItem = new javax.swing.JMenuItem();
        fileMenuExit = new javax.swing.JMenuItem();
        fileMenuWizard = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JSeparator();
        jSeparator5 = new javax.swing.JSeparator();
        jSeparator8 = new javax.swing.JToolBar.Separator();
        jMenu2 = new javax.swing.JMenu();
        editMenuItemUndo = new javax.swing.JMenuItem();
        editMenuItemRedo = new javax.swing.JMenuItem();
        editMenuCopyItem = new javax.swing.JMenuItem();
        editMenuPasteItem = new javax.swing.JMenuItem();
        editMenuCutItem = new javax.swing.JMenuItem();
        FindReplaceMenuItem = new javax.swing.JMenuItem();
        GoToLineMenuItem = new javax.swing.JMenuItem();
        ConfigurationMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        customize = new javax.swing.JMenuItem();
        create = new javax.swing.JMenuItem();
        jMenuInfo = new javax.swing.JMenu();
        info = new javax.swing.JMenuItem();
        
        label.setVerticalAlignment(JLabel.TOP);
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setOpaque(true);
        //label.setForeground(Color.black);
        //label.setBorder(BorderFactory.createLineBorder(Color.black));
        
        Dimension maxSize = new Dimension(200, 200);
        
        completeMenu.setDefaultLookAndFeelDecorated(false);
        JFrame.setDefaultLookAndFeelDecorated(false);
        completeMenu.setUndecorated(true);
        autoComplete = new AutoComplete(completeMenu);

        toolbarContextMenu.setName("toolbarContextMenu"); 

        customizeMenuItem.setText(lang.Customize);
        customizeMenuItem.setName("customizeMenuItem"); 
        customizeMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                customizeMenuItemActionPerformed(evt);
            }
        });

        customizeDialog.setName("customizeDialog"); 
        templateDialog.setName("templateDialog"); 

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("xCira LaTeX Editor v1.3");
        JPanel content = (JPanel)getContentPane();
        KeyStroke stroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_SPACE, java.awt.event.InputEvent.CTRL_MASK);
        content.registerKeyboardAction(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	EnableAutoCompleteMenu();
            }
        }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
        javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("mainFrame"); 
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        toolbarPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        toolbarPanel.setAutoscrolls(true);
        toolbarPanel.setName("toolbarPanel"); 
        toolbarPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                BlueLatexEditor.this.mouseClicked(evt);
            }
        });
        toolbarPanel.setLayout(new javax.swing.BoxLayout(toolbarPanel, javax.swing.BoxLayout.LINE_AXIS));

        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); 
        
        jToolBar2.setRollover(true);
        jToolBar2.setName("jToolBar2"); 

        newButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_white.png"))); 
        newButton.setToolTipText(lang.New);
        newButton.setFocusable(false);
        newButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newButton.setName("newButton"); 
        newButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(newButton);

        openButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/folder_magnify.png"))); 
        openButton.setToolTipText(lang.Open);
        openButton.setFocusable(false);
        openButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        openButton.setName("openButton"); 
        openButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        openButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(openButton);

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/disk.png"))); 
        saveButton.setToolTipText(lang.Save);
        saveButton.setFocusable(false);
        saveButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveButton.setName("saveButton"); 
        saveButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(saveButton);

        jSeparator8.setName("jSeparator8"); 
        jToolBar1.add(jSeparator8);

        boldButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_bold.png"))); 
        boldButton.setToolTipText(lang.Bold);
        boldButton.setFocusable(false);
        boldButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        boldButton.setName("boldButton"); 
        boldButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        boldButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boldButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(boldButton);

        italicButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_italic.png"))); 
        italicButton.setToolTipText(lang.Italic);
        italicButton.setFocusable(false);
        italicButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        italicButton.setName("italicButton"); 
        italicButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        italicButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                italicButtonActionPerformed(evt);
            }
        });
        
        jToolBar1.add(italicButton);
        
        underlineButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_underline.png"))); 
        underlineButton.setToolTipText(lang.Underline);
        underlineButton.setFocusable(false);
        underlineButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        underlineButton.setName("underlineButton"); 
        underlineButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        underlineButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                underlineButtonActionPerformed(evt);
            }
        });

        jToolBar1.add(underlineButton);
        
        jSeparator3.setName("jSeparator3"); 
        jToolBar1.add(jSeparator3);
        
        footNoteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/eye.png"))); 
        footNoteButton.setToolTipText(lang.FootNote);
        footNoteButton.setFocusable(false);
        footNoteButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        footNoteButton.setName("footNoteButton"); 
        footNoteButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        footNoteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                footNoteButtonActionPerformed(evt);
            }
        });
        
        jToolBar1.add(footNoteButton);

        hrefButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/world.png"))); 
        hrefButton.setToolTipText(lang.HyperLink);
        hrefButton.setFocusable(false);
        hrefButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        hrefButton.setName("href"); 
        hrefButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        hrefButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hrefButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(hrefButton);

        

        jSeparator1.setName("jSeparator1"); 
        jToolBar1.add(jSeparator1);

        alignLeftButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_align_left.png"))); 
        alignLeftButton.setToolTipText(lang.AlignLeft);
        alignLeftButton.setFocusable(false);
        alignLeftButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        alignLeftButton.setName("alignLeftButton"); 
        alignLeftButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        alignLeftButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alignLeftButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(alignLeftButton);

        alignCenterButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_align_center.png"))); 
        alignCenterButton.setToolTipText(lang.AlignCenter);
        alignCenterButton.setFocusable(false);
        alignCenterButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        alignCenterButton.setName("alignCenterButton"); 
        alignCenterButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        alignCenterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alignCenterButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(alignCenterButton);

        alignRightButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_align_right.png"))); 
        alignRightButton.setToolTipText(lang.AlignRight);
        alignRightButton.setFocusable(false);
        alignRightButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        alignRightButton.setName("alignRightButton"); 
        alignRightButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        alignRightButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alignRightButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(alignRightButton);

        jSeparator2.setName("jSeparator2"); 
        jToolBar1.add(jSeparator2);

        cutButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/cut.png"))); 
        cutButton.setToolTipText(lang.Cut);
        cutButton.setFocusable(false);
        cutButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cutButton.setName("cutButton"); 
        cutButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        cutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cutButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(cutButton);

        copyButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/application_double.png"))); 
        copyButton.setToolTipText(lang.Copy);
        copyButton.setFocusable(false);
        copyButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        copyButton.setName("copyButton"); 
        copyButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        copyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(copyButton);

        pasteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_paste.png"))); 
        pasteButton.setToolTipText(lang.Paste);
        pasteButton.setFocusable(false);
        pasteButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        pasteButton.setName("pasteButton"); 
        pasteButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        pasteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pasteButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(pasteButton);

        jSeparator6.setName("jSeparator6"); 
        jToolBar1.add(jSeparator6);

        commentOutBtn.setText(lang.CommentOut);
        commentOutBtn.setFocusable(false);
        commentOutBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        commentOutBtn.setName("commentOutBtn"); 
        commentOutBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        commentOutBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commentOutBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(commentOutBtn);

        commentInBtn.setText(lang.CommentIn);
        commentInBtn.setFocusable(false);
        commentInBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        commentInBtn.setName("commentInBtn"); 
        commentInBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        commentInBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commentInBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(commentInBtn);

        createToolbarBtn.setText(lang.CreateToolbar);
        createToolbarBtn.setFocusable(false);
        createToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        createToolbarBtn.setName("createToolbarBtn"); 
        createToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        createToolbarBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createToolbarBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(createToolbarBtn);

        jSeparator7.setName("jSeparator7"); 
        jToolBar1.add(jSeparator7);

        jLabel1.setText(lang.ConvertTo + "   ");
        jLabel1.setName("jLabel1"); 
        jToolBar2.add(jLabel1);

        jComboBoxCovertTo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PDF", "DVI", "PS" }));
        jComboBoxCovertTo.setName("jComboBoxCovertTo");
        jComboBoxCovertTo.setMaximumSize(maxSize);
        jToolBar2.add(jComboBoxCovertTo);
        
        convertToPdfButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/building.png"))); 
        convertToPdfButton.setToolTipText(lang.ConvertTo);
        convertToPdfButton.setFocusable(false);
        convertToPdfButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        convertToPdfButton.setName("convertToPdfButton"); 
        convertToPdfButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        convertToPdfButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                convertToPdfButtonActionPerformed(evt);
            }
        });
        jToolBar2.add(convertToPdfButton);

        
        
        jComboBoxSections.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Sections"}));
        jComboBoxSections.setName("jComboBoxSections");
        jComboBoxSections.setMaximumSize(maxSize);
        jComboBoxSections.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jComboBoxSectionsActionPerformed(evt);
            }
        });
        jComboBoxSections.addFocusListener(new java.awt.event.FocusListener() {
        	public void focusGained(FocusEvent evt) {
        		jComboBoxSectionsOnClick();
        	}

			public void focusLost(FocusEvent e) {
				// TODO Auto-generated method stub
			}
        });
        jToolBar2.addSeparator(new Dimension(20,200));
        jToolBar2.add(jComboBoxSections);
        
        hiddenLabel.setName("hiddenLabel"); 

        btnPreview.setText(lang.Preview);
        btnPreview.setName("btnPreview"); 
        btnPreview.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPreviewActionPerformed(evt);
            }
        });
        
        btnPreviewSelected.setText(lang.PreviewSelected);
        btnPreviewSelected.setName("btnPreviewSelected"); 
        btnPreviewSelected.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btnPreviewSelectedActionPerformed(evt);
            }
        });

        prevButton.setText("<<");
        prevButton.setEnabled(false);
        prevButton.setName("prevButton"); 
        prevButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                prevButtonActionPerformed(evt);
            }
        });

        nextButton.setText(">>");
        nextButton.setEnabled(false);
        nextButton.setName("nextButton"); 
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        pagesTextField.setEditable(false);
        pagesTextField.setName("pagesTextField"); 
        pagesTextField.setHorizontalAlignment(JTextField.CENTER);
        

        jSplitPane1.setDividerLocation(350);
        jSplitPane1.setName("jSplitPane1");
        
        previewPanel1.setName("previewPanel1"); 
        jSplitPane1.setRightComponent(previewPanel1);

        jPanel1.setName("jPanel1"); 
        jPanel1.setLayout(new java.awt.BorderLayout());

        tab_Editors.setName("tab_Editors"); 
        jPanel1.add(tab_Editors, java.awt.BorderLayout.CENTER);

        jPanel2.setName("jPanel2"); 
        jPanel2.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setName("jScrollPane1"); 

        outputTextArea.setColumns(20);
        outputTextArea.setFont(new java.awt.Font("Tahoma", 0, 11)); 
        outputTextArea.setRows(5);
        outputTextArea.setDisabledTextColor(new java.awt.Color(255, 51, 51));
        outputTextArea.setEnabled(false);
        outputTextArea.setName("outputTextArea"); 
        jScrollPane1.setViewportView(outputTextArea);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        outputLabel.setText(lang.Output);
        outputLabel.setName("outputLabel"); 
        jPanel2.add(outputLabel, java.awt.BorderLayout.PAGE_START);

        jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setLeftComponent(jPanel1);

        jMenuBar1.setName("jMenuBar1"); 

        fileMenuExitItem.setText(lang.File);
        fileMenuExitItem.setName("fileMenuExitItem"); 

        fileMenuNewItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuNewItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_white.png"))); 
        fileMenuNewItem.setText(lang.New);
        fileMenuNewItem.setToolTipText(lang.CreateNewFile);
        fileMenuNewItem.setName("fileMenuNewItem"); 
        fileMenuNewItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuNewItemActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuNewItem);
        
        fileMenuWizard.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuWizard.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/wizard.png"))); 
        fileMenuWizard.setText(lang.LatexWizard);
        fileMenuWizard.setToolTipText(lang.OpenWizardMenu);
        fileMenuWizard.setName("fileMenuWizard");
        fileMenuWizard.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	wizardMenuItemActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuWizard);
        
        

        fileMenuOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuOpen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/folder_magnify.png"))); 
        fileMenuOpen.setText(lang.Open);
        fileMenuOpen.setToolTipText(lang.OpenExistingFile);
        fileMenuOpen.setName("fileMenuOpen"); 
        fileMenuOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuOpenActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuOpen);

        fileMenuSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/disk.png"))); 
        fileMenuSave.setText(lang.Save);
        fileMenuSave.setName("fileMenuSave"); 
        fileMenuSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuSaveActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuSave);

        fileMenuSaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        fileMenuSaveAs.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/saveas.png"))); 
        fileMenuSaveAs.setText(lang.SaveAs);
        fileMenuSaveAs.setName("fileMenuSaveAs"); 
        fileMenuSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuSaveAsActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuSaveAs);
        
        //fileMenuImport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        fileMenuImport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/package_add.png"))); 
        fileMenuImport.setText(lang.Import);
        fileMenuImport.setName("fileMenuImport"); 
        fileMenuImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuImportActionPerformed(evt);
            }
        });  
        
//      fileMenuExport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        fileMenuExport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/package_go.png"))); 
        fileMenuExport.setText(lang.Export);
        fileMenuExport.setName("fileMenuExport"); 
        fileMenuExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuExportActionPerformed(evt);
            }
        });
      

        fileMenuCloseItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        fileMenuCloseItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/close.png"))); 
        fileMenuCloseItem.setText(lang.Close);
        fileMenuCloseItem.setName("fileMenuCloseItem"); 
        fileMenuExitItem.add(fileMenuCloseItem);

        fileMenuExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/door_out.png"))); 
        fileMenuExit.setText(lang.Exit);
        fileMenuExit.setToolTipText(lang.Exit);
        fileMenuExit.setName("fileMenuExit"); 
        fileMenuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuExitActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuExit);

        jMenuBar1.add(fileMenuExitItem);

        jMenu2.setText(lang.Edit);
        jMenu2.setName("jMenu2"); 

        editMenuItemUndo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK));
        editMenuItemUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/arrow_undo.png"))); 
        editMenuItemUndo.setText(lang.Undo);
        editMenuItemUndo.setToolTipText(lang.Undo);
        editMenuItemUndo.setName("jMenuItemUndo"); 
        jMenu2.add(editMenuItemUndo);

        editMenuItemRedo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK));
        editMenuItemRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/arrow_redo.png"))); 
        editMenuItemRedo.setText(lang.Redo);
        editMenuItemRedo.setName("editMenuItemRedo"); 
        jMenu2.add(editMenuItemRedo);

        editMenuCopyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        editMenuCopyItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/application_double.png"))); 
        editMenuCopyItem.setText(lang.Copy);
        editMenuCopyItem.setToolTipText(lang.CopySelection);
        editMenuCopyItem.setName("editMenuCopyItem"); 
        editMenuCopyItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuCopyItemActionPerformed(evt);
            }
        });
        jMenu2.add(editMenuCopyItem);

        editMenuPasteItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        editMenuPasteItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_paste.png"))); 
        editMenuPasteItem.setText(lang.Paste);
        editMenuPasteItem.setToolTipText(lang.Paste);
        editMenuPasteItem.setName("editMenuPasteItem"); 
        editMenuPasteItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuPasteItemActionPerformed(evt);
            }
        });
        jMenu2.add(editMenuPasteItem);

        editMenuCutItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        editMenuCutItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/cut.png"))); 
        editMenuCutItem.setText(lang.Cut);
        editMenuCutItem.setToolTipText(lang.CutSelection);
        editMenuCutItem.setName("editMenuCutItem"); 
        editMenuCutItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuCutItemActionPerformed(evt);
            }
        });
        jMenu2.add(editMenuCutItem);

        FindReplaceMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK));
        FindReplaceMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/findreplace.png"))); 
        FindReplaceMenuItem.setText(lang.FindReplace);
        FindReplaceMenuItem.setName("FindReplaceMenuItem"); 
        FindReplaceMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FindReplaceMenuItemActionPerformed(evt);
            }
        });
        jMenu2.add(FindReplaceMenuItem);
        
        GoToLineMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
        GoToLineMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/gotoline.png"))); 
        GoToLineMenuItem.setText(lang.GoToLine);
        GoToLineMenuItem.setName("GoToLineMenuItem"); 
        GoToLineMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	GoToLineMenuItemActionPerformed(evt);
            }
        });
        jMenu2.add(GoToLineMenuItem);
        
        ConfigurationMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
        ConfigurationMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/configuration.png"))); 
        ConfigurationMenuItem.setText(lang.ConfigurationMenu);
        ConfigurationMenuItem.setName("ConfigurationMenuItem");
        ConfigurationMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	ConfigurationMenuItemActionPerformed(evt);
            }
        });
        jMenu2.add(ConfigurationMenuItem);
        
        jMenuBar1.add(jMenu2);

        jMenu1.setText(lang.Toolbar);
        jMenu1.setName("jMenu1"); 

        customize.setText(lang.Customize);
        customize.setName("customize");
        customize.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/customize_toolbar.png"))); 
        customize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                customizeMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(customize);

        create.setText(lang.Create);
        create.setName("create");
        create.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/create_toolbar.png")));
        create.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createToolbarBtnActionPerformed(evt);
            }
        });
        jMenu1.add(create);
        
        jMenu1.add(fileMenuImport);
        jMenu1.add(fileMenuExport);

        jMenuBar1.add(jMenu1);
        
        /* ilker */
        jMenuInfo.setText(lang.Info);
        jMenuInfo.setName("InfoMenu");
        
        info.setText("xCira");
        info.setName("info");
        info.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/information.png"))); 
        info.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                infoMenuItemActionPerformed(evt);
            }
        });
        jMenuInfo.add(info);
        
        jMenuBar1.add(jMenuInfo);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(toolbarPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
                            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
                            .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE))
                        .addComponent(hiddenLabel)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnPreview)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnPreviewSelected)
                        .addGap(350)                    
                        .addComponent(prevButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(pagesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(nextButton))
                        ))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(toolbarPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPreviewSelected)
                    .addComponent(prevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING))
                    .addComponent(pagesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPreview))
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(hiddenLabel)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 514, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
	protected void jComboBoxSectionsOnClick() {
		ph.FillSectionArray(this.tab_Editors, jComboBoxSections);
	}

	private void EnableAutoCompleteMenu(){
    	JTextPane jtp = new TextEditors().GetJTextPaneAt(this.tab_Editors, this.tab_Editors.getSelectedIndex());
    	autoComplete.setTextPane(jtp);
    	autoComplete.PopMenu();
    }

    Language lang = new Language();
    
    private void SysTray() {
    	final TrayIcon trayIcon;

    	if (_operatingSystem.contains("Windows") && SystemTray.isSupported()) {

    	    SystemTray tray = SystemTray.getSystemTray();
    	    Image image = Toolkit.getDefaultToolkit().getImage("tray.gif");
    	    
    	    	
    	    MouseListener mouseListener = new MouseListener() {
    	                
    	        public void mouseClicked(MouseEvent e) {
    	                             
    	        }

    	        public void mouseEntered(MouseEvent e) {
    	                             
    	        }

    	        public void mouseExited(MouseEvent e) {
    	                             
    	        }

    	        public void mousePressed(MouseEvent e) {
    	                             
    	        }

    	        public void mouseReleased(MouseEvent e) {
    	                             
    	        }
    	    };

    	    ActionListener exitListener = new ActionListener() {
    	        public void actionPerformed(ActionEvent e) {
    	            System.out.println("Exiting...");
    	            System.exit(0);
    	        }
    	    };
    	    
    	    ActionListener configListener = new ActionListener() {
    	        public void actionPerformed(ActionEvent e) {
    	        	ConfigurationMenuItemActionPerformed(e);
    	        }
    	    };
    	            
    	    PopupMenu popup = new PopupMenu();
    	    
    	    MenuItem defaultItem = new MenuItem(lang.Exit);
    	    defaultItem.addActionListener(exitListener);
    	    
    	    MenuItem configItem = new MenuItem(lang.ConfigurationMenu);
    	    configItem.addActionListener(configListener);
    	    
    	    popup.add(configItem);
    	    popup.add(defaultItem);
    	    

    	    trayIcon = new TrayIcon(image, "xCira Latex Editor", popup);

    	    ActionListener actionListener = new ActionListener() {
    	        public void actionPerformed(ActionEvent e) {
    	            trayIcon.displayMessage("Action Event", 
    	                "An Action Event Has Been Performed!",
    	                TrayIcon.MessageType.INFO);
    	        }
    	    };
    	            
    	    trayIcon.setImageAutoSize(true);
    	    trayIcon.addActionListener(actionListener);
    	    trayIcon.addMouseListener(mouseListener);

    	    try {
    	        tray.add(trayIcon);
    	    } catch (AWTException e) {
    	        System.err.println("TrayIcon could not be added.");
    	    }

    	} else {

    	    //  System Tray is not supported

    	}
	}

	private void CreateConfigFile() throws IOException {
	    try
	    {
	    	FileReader fr = new FileReader("Configuration.xml");
	    	fr.close();
	    }	
	    catch( FileNotFoundException filenotfoundexxption ){
	    	
	    	Document domDoc = XmlHandler.createXmlDocument();
	    	Element configList = domDoc.createElement("Configuration");
	        Element configElements = domDoc.createElement("ProgramConfig") ;
	        Element miktexPath = domDoc.createElement("MiktexPath");
	        configElements.appendChild(miktexPath) ;
	        Element onTheFlyCompilation = domDoc.createElement("onTheFlyCompilation");
	        configElements.appendChild(onTheFlyCompilation);
	        Element Language = domDoc.createElement("Language");
	        configElements.appendChild(Language);
	        configList.appendChild(configElements);
	        domDoc.appendChild(configList) ;
	        
	        String xmlString = XmlHandler.createXmlString(domDoc) ;

	        try {
				FileWriter fw = new FileWriter(new File("Configuration.xml"));
				fw.write(xmlString);
				fw.flush();
				fw.close();
			} catch (IOException ex) {
				Logger.getLogger(AppConfigReader.class.getName()).log(Level.SEVERE,
						null, ex);
	    	}
	    }    
	}

	private void LoadToolbars() {
        String executionPath = System.getProperty("user.dir");
        executionPath = executionPath.replace("\\", "/") + "/AppConfig.xml";
        ToolBarHandler handler = ToolBarHandler.getHandler();
        handler.setContainer(toolbarPanel);
        //String url = getPathToJarfileDir(handler);
        try {
            //String temp = url + "/AppConfig.xml";
            handler.Generate(executionPath);//C:/Documents and Settings/kursattopcu/My Documents/NetBeansProjects/MyLatexEditor/src/mylatexeditor

            
            
            toolbarPanel.setVisible(true);
            outputTextArea.setText("Toolbars successfully installed...");
            toolbarPanel.revalidate();
        } catch (Exception ex) {
            outputTextArea.setText(ExceptionHandler.ProcessException(ex) + " PATH: " + executionPath);
        }
    }

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

        String executionPath = System.getProperty("user.dir");
        executionPath = executionPath.replace("\\", "/");
    	Tools tool = new Tools(executionPath + "/"/*"/src/com/meraklisina/latexeditor/mdi/"*/, "");
        tool.InitializeTextEditors(this.tab_Editors);

        // add undo/redo to loaded text editors
        UndoRedo u = new UndoRedo();
        u.applyToTextEditors(this.tab_Editors, this.editMenuItemUndo, this.editMenuItemRedo);

        this.LoadToolbars();
        this.cf=new CustomizeForm(this.customizeDialog);
        this.customizeDialog.getContentPane().add(cf);
        
        this.tf = new TemplateForm(this.templateDialog, this.tab_Editors);
        this.templateDialog.getContentPane().add(tf);
    }//GEN-LAST:event_formWindowOpened

    private void saveState() {
        TextEditors ClsTextEditor = new TextEditors();
        if (ClsTextEditor.WriteIntoXmlTextEditor()) {
            while (ClsTextEditor.getEditors().size() > 0) {
                ClsTextEditor.CloseTabAtDialog(this.tab_Editors, ClsTextEditor.GetLastChangedEditor(this.tab_Editors));
            }
        }
        ToolBarHandler.getHandler().serializeToolBars();
    }

    public void NewTab() {
        TextEditors ClsTextEditor = new TextEditors();
        ClsTextEditor.AddTab(tab_Editors);

        // apply undo/redo functionality to the new tab
        new UndoRedo(ClsTextEditor.GetJTextPane(tab_Editors), this.editMenuItemUndo, this.editMenuItemRedo);
    }

    public void OpenFile() {
        ActionOpen ClsActionOpen = new ActionOpen();
        ClsActionOpen.OpenDialog(tab_Editors);

         // apply undo/redo functionality to the new tab
         TextEditors ClsTextEditor = new TextEditors();
         new UndoRedo(ClsTextEditor.GetJTextPane(this.tab_Editors), this.editMenuItemUndo, this.editMenuItemRedo);
    }

    public boolean Save(boolean IsSaveAs) {
        TextEditors ClsTextEditor = new TextEditors();
        return ClsTextEditor.SaveTab(this.tab_Editors, IsSaveAs);
    }


    /*
     * Bold Toolbar Button Action Handler Method
     * */
    private void boldButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boldButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\textbf{" + selected + "}";
        replaceSelectedText(editors, replacement);
}//GEN-LAST:event_boldButtonActionPerformed

    public static String getSelectedText(TextEditors editors){
        String selectedText = editors.GetText(tab_Editors);
        if(selectedText == null)
            selectedText = "";
        return selectedText;
    }

    public static void replaceSelectedText(TextEditors editors, String replacement){
        int tabIndex = tab_Editors.getSelectedIndex();
        editors.ReplaceSelectedText(tab_Editors, tabIndex, replacement);
    }
    /*
     * File->Open Menu Item Action Handler
     * */
    private void fileMenuOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuOpenActionPerformed
        //openButtonActionPerformed(evt);
        OpenFile();
    }//GEN-LAST:event_fileMenuOpenActionPerformed

    /*
     * New File Toolbar Button Action Handler
     * */
    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed

        NewTab();
    }//GEN-LAST:event_newButtonActionPerformed

    /*
     * Save Toolbar Button Action Handler
     * */
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        Save(false);
        
        if (_onTheFlyCompilation)
        {
	        try {
	            if (generatePdf()) {
	                DocNumberOfPages = Notify(tempPdfFileName);
	            }
	        } catch (FileNotFoundException ex) {
	            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
	        } catch (IOException ex) {
	            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
	        }
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    /*
     * File->New Menu Item Action Handler
     * */
    private void fileMenuNewItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuNewItemActionPerformed
        //newButtonActionPerformed(evt);
        NewTab();
}//GEN-LAST:event_fileMenuNewItemActionPerformed

    /*
     * File->Save Menu Item Action Handler
     * */
    private void fileMenuSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuSaveActionPerformed
        Save(false);
        
        if (_onTheFlyCompilation)
        {
	        try {
	            if (generatePdf()) {
	                DocNumberOfPages = Notify(tempPdfFileName);
	            }
	        } catch (FileNotFoundException ex) {
	            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
	        } catch (IOException ex) {
	            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
	        }
        }
    }//GEN-LAST:event_fileMenuSaveActionPerformed

    /*
     * File->SaveAs Action Handler
     * */
    private void fileMenuSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuSaveAsActionPerformed
        Save(true);
    }//GEN-LAST:event_fileMenuSaveAsActionPerformed
    
    private void fileMenuImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuSaveAsActionPerformed
        new ToolbarTransporter(true);
    }
    
    private void fileMenuExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuSaveAsActionPerformed
    	new ToolbarTransporter(false);
    }

    /*
     * Italic Toolbar Button Action Handler
     * */
    private void italicButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hrefButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\it{" + selected + "}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_italicButtonActionPerformed

    /*
     * Underline Toolbar Button Action Handler Method
     * */
    private void footNoteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_footNoteButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\footnote[number]{" + selected + "}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_footNoteActionPerformed

    /*
     * Underline Toolbar Button Action Handler Method
     * */
    
    private void hrefButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hrefButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
    
        String replacement = "\\href{url}{" + selected + "}";
        replaceSelectedText(editors, replacement);
        
        try{
        	InsertPackage("hyperref");
        } catch (Exception ee) {
        	System.out.println("Ooopss");
        }	
    
    }//GEN-LAST:event_hrefButtonActionPerformed

    /*
     * Underline Toolbar Button Action Handler Method
     * */
    
    private void InsertPackage(String packageName)
    {
    	TextEditors editors = new TextEditors();
        JTextPane jtp = editors.GetJTextPane(tab_Editors);
        String documentTxt = jtp.getText();
        
        if(!documentTxt.contains("\\usepackage{" + packageName + "}") || documentTxt.contains("%\\usepackage{" + packageName + "}"))
        {
            try{
            	ph.GoToSelectedLine(FindPackageInsertionPoint(), tab_Editors);
            	String replacement = "\\usepackage{"+ packageName + "}\n"; 
                replaceSelectedText(editors, replacement);
//	        	jtp.getDocument().insertString(FindPackageInsertionPoint(), "\n\\usepackage{" + packageName + "}\n", null);	
	        } catch (Exception ee) {
	        	System.out.println("Ooopss");
	        }
        }
    }
    
    private int FindPackageInsertionPoint()
    {
    	int number = 0;
    	
    	TextEditors editors = new TextEditors();
        JTextPane jtp = editors.GetJTextPane(tab_Editors);
        String documentTxt = jtp.getText();

        number = documentTxt.indexOf("\\usepackage");
        if(!(number > 0))
        {
        	number = documentTxt.indexOf("\\begin");
        }
        number = ph.FindLineNumberAtCaretPosition(number, tab_Editors);
        
        return number;
    }
    
    private void underlineButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_underlineButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\underline{" + selected + "}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_underlineButtonActionPerformed

    /*
     * Align Left Toolbar Button Action Handler Method
     * */
    private void alignLeftButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alignLeftButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\begin{flushleft}\n" + selected + "\n\\end{flushleft}\n";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_alignLeftButtonActionPerformed

    /*
     * Align Center Toolbar Button Action Handler Method
     * */
    private void alignCenterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alignCenterButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\begin{center}\n" + selected + "\n\\end{center}\n";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_alignCenterButtonActionPerformed

    /*
     * Align Right Toolbar Button Action Handler Method
     * */
    private void alignRightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alignRightButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\begin{flushright}\n" + selected + "\n\\end{flushright}\n";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_alignRightButtonActionPerformed

    /*
     * Cut Toolbar Button Action Handler Method
     * */
    private void cutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cutButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "";
        replaceSelectedText(editors, replacement);
        hiddenLabel.setVisible(false);
        hiddenLabel.setText(selected);
    }//GEN-LAST:event_cutButtonActionPerformed

    /*
     * Copy Toolbar Button Action Handler Method
     * */
    private void copyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        hiddenLabel.setVisible(false);
        hiddenLabel.setText(selected);
    }//GEN-LAST:event_copyButtonActionPerformed

    /*
     * Paste Toolbar Button Action Handler Method
     * */
    private void pasteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pasteButtonActionPerformed
        TextEditors editors = new TextEditors();
        replaceSelectedText(editors, hiddenLabel.getText());
    }//GEN-LAST:event_pasteButtonActionPerformed

    /*
     * Edit->Copy Menu Item Action Handler Method
     * */
    private void editMenuCopyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuCopyItemActionPerformed
        copyButtonActionPerformed(evt);
    }//GEN-LAST:event_editMenuCopyItemActionPerformed

    /*
     * Edit->Paste Menu Item Action Handler Method
     * */
    private void editMenuPasteItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuPasteItemActionPerformed
        pasteButtonActionPerformed(evt);
    }//GEN-LAST:event_editMenuPasteItemActionPerformed

    /*
     * Open Button Action Handler Method
     * */
    private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed

        OpenFile();
    }//GEN-LAST:event_openButtonActionPerformed

    /*
     * Bold Toolbar Button Action Handler Method
     * */
    private void commentOutBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commentOutBtnActionPerformed
        TextEditors editors = new TextEditors();
        editors.CommentInOut(tab_Editors, true, "%");
}//GEN-LAST:event_commentOutBtnActionPerformed

    /*
     * File->Exit Menu Item Action Handler Method
     * */
    private void fileMenuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuExitActionPerformed
        System.exit(0);
}//GEN-LAST:event_fileMenuExitActionPerformed

    /*
     * Build Toolbar Button Action Handler Method
     * */
    private void convertToPdfButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_convertToPdfButtonActionPerformed

         try{
        	 TextEditors ClsTextEditor = new TextEditors();
        	 
        	 // IT : Check if the file is changed and pop up question dialog
        	 if(ClsTextEditor.GetIsTextChanged(tab_Editors.getSelectedIndex()))
        	 {
	             int DialogResult = JOptionPane.showConfirmDialog(
	                     null,
	                     "Do you want to save the changes on '" + tab_Editors.getTitleAt(tab_Editors.getSelectedIndex()) + "'?",
	                     "New Page",
	                     JOptionPane.YES_NO_CANCEL_OPTION);

	             if(DialogResult == JOptionPane.YES_OPTION)
	             {
	            	if(!Save(false))
	            		return;
	            	outputTextArea.setText("\nThe file saved successfully: ");
	             }
	             else if (DialogResult == JOptionPane.CANCEL_OPTION)
	             {
	            	return; 
	             }
        	 }
         }catch(Exception er){
            outputTextArea.setText("\nThe file cannot be saved!\nOperation cancelled");
            return;
         }

        try{
            String selectedBuilder = (String)jComboBoxCovertTo.getSelectedItem();
            MixTexStuff mixtex = new MixTexStuff();
            if(selectedBuilder.equalsIgnoreCase("DVI")){
                mixtex.buildProcess(latexExe, outputTextArea, tab_Editors);
            }else if(selectedBuilder.equalsIgnoreCase("PDF")){
                mixtex.buildProcess(pdflatexExe, outputTextArea, tab_Editors);
            }else if(selectedBuilder.equalsIgnoreCase("PS")){
                mixtex.buildProcess(dvipsExe, outputTextArea, tab_Editors);
            }
        }catch(Exception ee){
            outputTextArea.setText("\nError! Operation cannot be completed.");
        	ee.printStackTrace();
        }     
    }//GEN-LAST:event_convertToPdfButtonActionPerformed
    
    ProjectHelpers ph = new ProjectHelpers();
    
    private void jComboBoxSectionsActionPerformed(java.awt.event.ActionEvent ev)
    {
    	String selection = jComboBoxSections.getItemAt(0).toString();
		if (!selection.equalsIgnoreCase("No Section"))
		{
			int lineNumber = ph.GetLineNumberOfSection(jComboBoxSections.getSelectedIndex());
			ph.GoToSelectedLine(lineNumber, this.tab_Editors);
    	}
    }
    
    private void commentInBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commentInBtnActionPerformed
        TextEditors editors = new TextEditors();
        editors.CommentInOut(tab_Editors, false, "%");
    }//GEN-LAST:event_commentInBtnActionPerformed


    private void mouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mouseClicked
        if(evt.getButton()==MouseEvent.BUTTON3){
            mouseRightClicked(evt);
        }
}//GEN-LAST:event_mouseClicked
    private void mouseRightClicked(java.awt.event.MouseEvent evt) {
        // delete old ones
        this.toolbarContextMenu.removeAll();
        // add new toolbar menuitems
        ToolBarHandler handler=ToolBarHandler.getHandler();
        for(LatexToolBar tb:handler.getToolbars()){
            toolbarContextMenu.add(new LatexToolbarMenuItem(tb));
        }
        toolbarContextMenu.add(new JSeparator());
        toolbarContextMenu.add(this.customizeMenuItem);
        // display popupmenu
        this.toolbarContextMenu.show(this, evt.getXOnScreen(), evt.getYOnScreen());
    }
    private void editMenuCutItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuCutItemActionPerformed
        cutButtonActionPerformed(evt);
    }//GEN-LAST:event_editMenuCutItemActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        saveState();
    }//GEN-LAST:event_formWindowClosing

    private void customizeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_customizeMenuItemActionPerformed
        this.cf.reload();
        this.customizeDialog.setVisible(true);
    }
    
    private void infoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_customizeMenuItemActionPerformed
    	NewTab();
    	JTextPane jtp = new TextEditors().GetJTextPaneAt(this.tab_Editors, this.tab_Editors.getSelectedIndex());
    	
		String fileName;
		
		fileName = "/com/meraklisina/latexeditor/resources/InfoFiles/" + _language + ".txt";
				
		try{
			BufferedReader input =  new BufferedReader(new FileReader(new File(new URI(getClass().getResource(fileName).toString()))));
			
			String line;
	        while (( line = input.readLine()) != null)
			{
	        	jtp.getDocument().insertString(jtp.getDocument().getLength(), line + "\n", null);
			}
		}catch (Exception e){
		      System.err.println("Error: " + e.getMessage());
	    }
    }
    
    private void wizardMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_customizeMenuItemActionPerformed
    	NewTab();
    	JTextPane jtp = new TextEditors().GetJTextPaneAt(this.tab_Editors, this.tab_Editors.getSelectedIndex());
    	this.tf.SetTextPane(jtp);
        this.templateDialog.setVisible(true);
    }

    private void FindReplaceMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FindReplaceMenuItemActionPerformed
        JDialog dialog=new JDialog();
        FindReplace findReplace=new FindReplace(dialog, this.tab_Editors);
        dialog.getContentPane().add(findReplace);

        dialog.setTitle("Find/Replace");
        dialog.setSize(400, 175);
        dialog.setLocation((int)this.getLocation().getX() + 200, (int)this.getLocation().getY() + 200);
        dialog.setResizable(false);
        dialog.setModal(true);
        dialog.setVisible(true);

    }
    
    private void GoToLineMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FindReplaceMenuItemActionPerformed
        JDialog dialog=new JDialog();
        GoToLine goToLine=new GoToLine(dialog, this.tab_Editors);
        dialog.getContentPane().add(goToLine);

        dialog.setTitle(lang.GoToLine);
        dialog.setSize(250, 100);
        dialog.setLocation((int)this.getLocation().getX() + 200, (int)this.getLocation().getY() + 200);
        dialog.setResizable(false);
        dialog.setModal(true);
        dialog.setVisible(true);

    }
    
    private void ConfigurationMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
        JDialog dialog=new JDialog();
        ConfigurationMenu configMenu=new ConfigurationMenu(dialog);
        dialog.getContentPane().add(configMenu);

        dialog.setTitle(lang.ConfigurationMenu);
        dialog.setSize(500, 150);
        dialog.setLocation((int)this.getLocation().getX() + 200, (int)this.getLocation().getY() + 200);
        dialog.setResizable(false);
        dialog.setModal(true);
        dialog.setVisible(true);
        
    }

    /**
     * Generates the pdf of the currently selected tab document.
     * @return
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    private boolean generatePdf() throws FileNotFoundException, IOException {
        TextEditors ClsTextEditor = new TextEditors();
        int index = tab_Editors.getSelectedIndex();
        JTextPane textPane = ClsTextEditor.GetJTextPane(tab_Editors);
        String filePath = ClsTextEditor.GetRealPath(index);
        currentFileName = filePath;
        Process proc = null;
        ProcessBuilder pbuilder = new ProcessBuilder();
        pbuilder.directory(new File(getFilePath(currentFileName)));
        BufferedReader input;
        //boş tmp bi pdffile ver
        //changeDisplay();

        if (!new File(currentFileName).exists()) {
            return false;
        }
        try {
            if (_operatingSystem.contains("Linux"))
            {	
            	String[] exLinux = {"pdflatex", "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", getFilePath(currentFileName), currentFileName};
            	pbuilder.command(exLinux);
            }
            else if (_operatingSystem.contains("Windows"))
            {
            	String[] exWindows = {BlueLatexEditor._miktexPath +"pdflatex.exe", "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", getFilePath(currentFileName), currentFileName};
            	pbuilder.command(exWindows);
            }
            
            proc = pbuilder.start();
            String line;

            input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            while ((line = input.readLine()) != null) {
                outputTextArea.setText("[output] " + line + "\n");
            }
            input.close();

            input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            while ((line = input.readLine()) != null) {
                outputTextArea.setText("[errors] " + line + "\n");
            }
            input.close();

            ReadAndShowLogForWarningAndErrors(currentFileName);
            
            String pathDirectory;
            int indexOfBSlash = currentFileName.lastIndexOf("\\");
            if(indexOfBSlash >= 0)
            {
            	pathDirectory = currentFileName.substring(0, indexOfBSlash);
            }
            //IT : For linux..
            else
            {
            	pathDirectory = getFilePath(currentFileName);
            }
            File oldTempFile;           
            if(indexOfBSlash >= 0)
            {
            	oldTempFile = new File(pathDirectory + "\\" + tempPdfFileName);
            }
            else
            {
            	oldTempFile = new File(getFilePath(currentFileName) + "/" + tempPdfFileName);
            }
            
            
            tempPdfFileName = tempStatic + Integer.toString(tempCounter);
            tempCounter++;

            copyToTempPdf(currentFileName, tempPdfFileName);
            if(oldTempFile.exists()){
                try{
                    oldTempFile.deleteOnExit();
                }
                catch(SecurityException sec){
                    String error = "sec exception";
                }
                catch(Exception exs){
                    String error = exs.getMessage();
                }
                
            }
            
            int value = proc.waitFor();
            if (value != 0) {
                return false;
            }

            return true;
        } catch (Throwable e) {
            outputTextArea.setText(outputTextArea.getText() + "\npdflatex: command not found " + e.getMessage()+ e.toString());
            return false;
        }
        finally {
            if (proc != null) {
                try {
                    proc.getInputStream().close();
                    proc.getOutputStream().close();
                    proc.getErrorStream().close();
                    proc.destroy();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    private boolean generatePdfSelectedText() throws FileNotFoundException, IOException {
        TextEditors ClsTextEditor = new TextEditors();
        int index = tab_Editors.getSelectedIndex();
        JTextPane textPane = ClsTextEditor.GetJTextPane(tab_Editors);
        if (textPane.getSelectedText() == null)
        {
        	outputTextArea.setText("\nNo text selected !!! Please select text to preview\n");
        	return false;
        }
        String filePath = ClsTextEditor.GetRealPath(index);
        String filePathSelected = filePath.substring(0, filePath.length()-4) + "s" + ".tex";
        currentFileName = filePathSelected;
        Process proc = null;
        ProcessBuilder pbuilder = new ProcessBuilder();
        pbuilder.directory(new File(getFilePath(currentFileName)));
        BufferedReader input;
        
        try
        {
        	FileWriter writeFile = new FileWriter(filePathSelected);
        	
        	String CompleteFile = textPane.getText();
        	String CompleteString =  CompleteFile.substring(0,CompleteFile.indexOf("\\begin{document}")+16) + "\n" + textPane.getSelectedText() + "\n" + "\\end{document}";
            writeFile.write(CompleteString);
            writeFile.close();
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null,ex.getMessage(),"File error",JOptionPane.ERROR_MESSAGE);
        }

        if (!new File(currentFileName).exists()) {
        	outputTextArea.setText("\nNothing to preview !!!\n");
            return false;
        }
        try {
            if (_operatingSystem.contains("Linux"))
            {	
            	String[] exLinux = {"pdflatex", "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", getFilePath(currentFileName), currentFileName};
            	pbuilder.command(exLinux);
            }
            else if (_operatingSystem.contains("Windows"))
            {
            	String[] exWindows = {BlueLatexEditor._miktexPath +"pdflatex.exe", "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", getFilePath(currentFileName), currentFileName};
            	pbuilder.command(exWindows);
            }
            
            proc = pbuilder.start();
            String line;

            input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            while ((line = input.readLine()) != null) {
                outputTextArea.setText("[output] " + line + "\n");
            }
            input.close();

            input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            while ((line = input.readLine()) != null) {
                outputTextArea.setText("[errors] " + line + "\n");
            }
            input.close();
            
            String pathDirectory;
            int indexOfBSlash = currentFileName.lastIndexOf("\\");
            if(indexOfBSlash >= 0)
            {
            	pathDirectory = currentFileName.substring(0, indexOfBSlash);
            }
            //IT : For linux..
            else
            {
            	pathDirectory = getFilePath(currentFileName);
            }
            File oldTempFile;           
            if(indexOfBSlash >= 0)
            {
            	oldTempFile = new File(pathDirectory + "\\" + tempPdfFileName);
            }
            else
            {
            	oldTempFile = new File(getFilePath(currentFileName) + "/" + tempPdfFileName);
            }
            
            
            tempPdfFileName = tempStatic + Integer.toString(tempCounter);
            tempCounter++;

            copyToTempPdf(currentFileName, tempPdfFileName);
            if(oldTempFile.exists()){
                try{
                    oldTempFile.deleteOnExit();
                }
                catch(SecurityException sec){
                    String error = "sec exception";
                }
                catch(Exception exs){
                    String error = exs.getMessage();
                }
                
            }
            int value = proc.waitFor();
            if (value != 0) {
            	outputTextArea.setText("\nNothing to preview !!!\n");
                return false;
            }
            return true;
        } catch (Throwable e) {
            outputTextArea.setText(outputTextArea.getText() + "\npdflatex: command not found " + e.getMessage()+ e.toString());
            return false;
        }
        finally {
            if (proc != null) {
                try {
                    proc.getInputStream().close();
                    proc.getOutputStream().close();
                    proc.getErrorStream().close();
                    proc.destroy();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    // Alper Selvi
    // This function shows the errors and warnings that exists on the log file.
    private void ReadAndShowLogForWarningAndErrors(String FileName) throws IOException {
		FileReader fr = new FileReader(FileName.substring(0,FileName.lastIndexOf("."))+".log");
		BufferedReader br = new BufferedReader(fr);
		String LogFile = null;
		String TextToWrite = "";
		
		while (true)
		{
			try
			{
				LogFile = br.readLine();
				if (LogFile.contains("LaTeX Error") || LogFile.contains("LaTeX Warning"))
				{
					TextToWrite = TextToWrite + LogFile + "\n";
				}
			}
			catch (Throwable e) {
	            break;
			}
		}
		
		outputTextArea.setText(outputTextArea.getText()+ "\n" + TextToWrite);
	}

	/**
     * Copies the content of tex file to a new file
     * @param pathOriginal the path of the tex file
     * @param tempFileName name of the file destination file
     * @throws java.io.IOException
     */
    public void copyToTempPdf(String pathOriginal, String tempFileName) throws IOException{
        //changeDisplay();
        int indexOfBSlash = pathOriginal.lastIndexOf("\\");
        String pathDirectory;
        if(indexOfBSlash >= 0)
        {
        	pathDirectory = pathOriginal.substring(0, indexOfBSlash);
        }
        else
        {
        	pathDirectory = getFilePath(currentFileName);
        }
        String pathOriginalPdf = pdfExt(pathOriginal);
        String pathTemp;
        if(indexOfBSlash >= 0)
        {
        	pathTemp = pathDirectory + "\\" + tempFileName;
        }
        else
        {
        	pathTemp = pathDirectory = getFilePath(currentFileName) + "/" + tempFileName;
        }
        File fileOriginal = new File(pathOriginalPdf);
        File fileTemp = new File(pathTemp);

        try {
            InputStream in = new FileInputStream(fileOriginal);
            OutputStream out = new FileOutputStream(fileTemp);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0){
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.getMessage());
        }
        fileTemp.deleteOnExit();
    }

    /**
     * Returns the pdf extension string of the tex file
     * @param texFilename name of the tex file
     * @return   string with pdf extension
     */
    private String pdfExt(String texFilename) {
        return texFilename.replaceFirst("[.][a-zA-Z]+$", ".pdf");
    }

    /**
     * Changes the preview to the given tex file's pdf
     * @param texFileName tex file name that will be screen pn preview panel. Not the absolute path. Just file name
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public void changeDisplay(String texFileName) throws FileNotFoundException, IOException{
        int indexOfBSlash = currentFileName.lastIndexOf("\\");
        String pathDirectory = currentFileName.substring(0, indexOfBSlash);
        File fileTex = new File(pathDirectory + "\\" + texFileName);
        //File file = new File(pdfExt("C:\\Documents and Settings\\vedat.ekiz\\Desktop\\yyyy\\tmp.tex"));
        File filePdf = new File(pdfExt(fileTex.getAbsolutePath()));
        try{
            OutputStream out = new FileOutputStream(fileTex);
            String def = "\\documentclass{article}\n\\begin{document}\nERROR\n\\end{document}";
            byte[] buff = def.getBytes();
            out.write(buff, 0, buff.length);
        }catch(Exception ex){

        }
        RandomAccessFile raf = new RandomAccessFile(filePdf, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        pdffile = new PDFFile(buf);
        previewPanel1.Update(pdffile, 1, true);
    }

    private String getFilePath(String fileName) {
         String newStr = "";
        try {
            //String[] Str = fileName.split(File.separator);
            String[] Str = fileName.split("\\" + File.separator);
            if (Str.length == 0) {
                return null;
            }

            for (int i = 0; i < Str.length - 1; i++) {
                newStr += Str[i] + File.separatorChar;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return newStr;
    }

    public int Notify(String fileName) {
        return Notify(true, fileName);
    }

    /**
     * 
     * @param if the page will be refreshed then true, otherwise false
     * @param fileName the file name to be previewed
     * @return the total number of pages
     */
    public int Notify(boolean hard, String fileName) {
        if (previewPanel1 != null) {
            try {
                ByteBuffer buf;
                if (hard) { // file needs to be refreshed
                    //File file = new File(pdfExt(this.currentFileName));
                	String filePath;
                	if(this.currentFileName.lastIndexOf("\\") >= 0)
                	{
                		filePath = this.currentFileName.substring(0, this.currentFileName.lastIndexOf("\\")) + "\\" + fileName;
                	}
                	else
                	{
                		filePath = getFilePath(currentFileName) + "/" + fileName;                		
                	}
                    
                	File file = new File(pdfExt(filePath));
                    RandomAccessFile raf = new RandomAccessFile(file, "r");
                    FileChannel channel = raf.getChannel();
                    buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
                    pdffile = new PDFFile(buf);
                    raf.close();
                    buf.clear();
                    channel.close();
                }
                previewPanel1.Update(pdffile, LastPageDisplayed, hard);
                final int retval = pdffile.getNumPages();

                if (hard) {
                    if (LastPageDisplayed != 1) {
                        prevButton.setEnabled(true);
                    }
                    if (LastPageDisplayed < retval) {
                        nextButton.setEnabled(true);
                    }
                    if (retval < LastPageDisplayed) {
                        LastPageDisplayed = retval;
                        nextButton.setEnabled(false);
                        previewPanel1.Update(pdffile, LastPageDisplayed, false);
                    }
                }
                final int page = LastPageDisplayed;
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        pagesTextField.setText(page + "/" + retval);
                    }
                });

                return retval;
            } catch (IOException ex) {
                Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return -1;
    }

    private void btnPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviewActionPerformed
        if(!Save(false))
        	return;
        
        btnPreview.setEnabled(false);
        
        try {
            if (generatePdf()) {
                DocNumberOfPages = Notify(tempPdfFileName);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        btnPreview.setEnabled(true);
    }
        
    private void btnPreviewSelectedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviewActionPerformed
       
    	btnPreviewSelected.setEnabled(false);
    	
    	try {
            if (generatePdfSelectedText()) {
            	DocNumberOfPages = Notify(tempPdfFileName);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        btnPreviewSelected.setEnabled(true);
    }

    private void prevButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_prevButtonActionPerformed
		if (LastPageDisplayed > 1) {
        LastPageDisplayed--;
        Notify(false, tempPdfFileName);
        if (LastPageDisplayed == 1) {
            prevButton.setEnabled(false);
        }
        nextButton.setEnabled(true);
		}
    }

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        if (LastPageDisplayed < DocNumberOfPages) {
            LastPageDisplayed++;
            Notify(false, tempPdfFileName);
            prevButton.setEnabled(true);
            if (LastPageDisplayed == DocNumberOfPages) {
                nextButton.setEnabled(false);
            }
        }
    }

    private void createToolbarBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createToolbarBtnActionPerformed
        JDialog dia = new JDialog();
        DynamicToolbarWizard wizard = new DynamicToolbarWizard(dia);
        dia.getContentPane().add(wizard);

        dia.setTitle("Toolbar Wizard");
        dia.setSize(600, 450);
        //dialog.setLocation((int)mainPanel.getLocation().getX() + 200, (int)mainPanel.getLocation().getY() + 200);
        dia.setResizable(true);
        dia.setModal(true);
        dia.setVisible(true);

        while(wizard.hasFocus()){
            //wait until button created
        }

        if(wizard.getToolbar() != null){
            //int toolbarCount = ToolBarHandler.getHandler().getToolbars().size();
            ToolBarHandler.getHandler().getToolbars().add(wizard.getToolbar());
            ToolBarHandler.getHandler().serializeToolBars();
        }
    }//GEN-LAST:event_createToolbarBtnActionPerformed

    /*
     * Dyanmic LaTeX Toolbar Buttons Action Handler Method
     * THIS METHOD IS FOR v1.1
     * */
    public static void PerformLatexButtonAction(LatexButton btn) {
        try {
            TextEditors editors = new TextEditors();
            String expression = btn.getExpressionTemplate();
            if (getSelectedText(editors).isEmpty()) {
                replaceSelectedText(editors, expression);
            } else {
                String prefix = btn.getPrefix();
                String suffix = btn.getSuffix();
                String selected = getSelectedText(editors);
                if(prefix == null)
                    prefix = "";

                if(suffix == null)
                    suffix = "";
                
                replaceSelectedText(editors, prefix + selected + suffix);
            }
        } catch (Exception ex) {
            outputTextArea.setText("Error: " + ex.getMessage());
        }
    }

    private void LoadSettings()
    {
    	XmlHandler ConfigurationHandler = new XmlHandler("Configuration.xml");
    	    	    	
    	NodeList config = ConfigurationHandler.GetElementsByTagName("ProgramConfig");
    	
    	int a = config.getLength();
    	if (a < 1)
    		return;
    	
    	Node Configuration = config.item(0);
    	_miktexPath = (ConfigurationHandler.GetChildNodeValue(Configuration, "MiktexPath"));
    	String CompilationChoice = ConfigurationHandler.GetChildNodeValue(Configuration, "onTheFlyCompilation");
    	if(CompilationChoice != null)
    	{
    		if (CompilationChoice.equalsIgnoreCase("Yes"))
        		_onTheFlyCompilation = true;
        	else
        		_onTheFlyCompilation = false;    		
    	}
    	else
    	{
    		_onTheFlyCompilation = false;
    	}
    	String LanguageChoice = (ConfigurationHandler.GetChildNodeValue(Configuration, "Language"));
    	
    	if (LanguageChoice == null) 
    		_language =  "English";
    	else
    		_language = LanguageChoice;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {                	
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                }
                _BlueLatexEditorIns = new BlueLatexEditor();
                _BlueLatexEditorIns.setVisible(true);
            }
        });
    }
    public String commandResult;
    private CustomizeForm cf=null;
    private TemplateForm tf=null;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem FindReplaceMenuItem;
    private javax.swing.JMenuItem GoToLineMenuItem;
    private javax.swing.JMenuItem ConfigurationMenuItem;
    private javax.swing.JButton alignCenterButton;
    private javax.swing.JButton alignLeftButton;
    private javax.swing.JButton alignRightButton;
    private javax.swing.JButton boldButton;
    private javax.swing.JButton btnPreview;
    private javax.swing.JButton btnPreviewSelected;
    private javax.swing.JButton commentInBtn;
    private javax.swing.JButton commentOutBtn;
    private javax.swing.JButton convertToPdfButton;
    private javax.swing.JButton copyButton;
    private javax.swing.JMenuItem create;
    private javax.swing.JButton createToolbarBtn;
    private javax.swing.JMenuItem customize;
    private javax.swing.JMenuItem info;
    private javax.swing.JDialog customizeDialog;
    private javax.swing.JDialog templateDialog;
    private javax.swing.JMenuItem customizeMenuItem;
    private javax.swing.JButton cutButton;
    private javax.swing.JMenuItem editMenuCopyItem;
    private javax.swing.JMenuItem editMenuCutItem;
    private javax.swing.JMenuItem editMenuItemRedo;
    private javax.swing.JMenuItem editMenuItemUndo;
    private javax.swing.JMenuItem editMenuPasteItem;
    private javax.swing.JMenuItem fileMenuCloseItem;
    private javax.swing.JMenuItem fileMenuExit;
    private javax.swing.JMenuItem fileMenuWizard;
    private javax.swing.JMenu fileMenuExitItem;
    private javax.swing.JMenuItem fileMenuNewItem;
    private javax.swing.JMenuItem fileMenuOpen;
    private javax.swing.JMenuItem fileMenuSave;
    private javax.swing.JMenuItem fileMenuSaveAs;
    private javax.swing.JMenuItem fileMenuImport;
    private javax.swing.JMenuItem fileMenuExport;
    private javax.swing.JLabel hiddenLabel;
    private javax.swing.JButton italicButton;
    private javax.swing.JButton footNoteButton;
    private javax.swing.JButton hrefButton;
    private javax.swing.JComboBox jComboBoxCovertTo;
    private javax.swing.JComboBox jComboBoxSections;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenuInfo;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JToolBar.Separator jSeparator6;
    private javax.swing.JToolBar.Separator jSeparator7;
    private javax.swing.JToolBar.Separator jSeparator8;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JButton newButton;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton openButton;
    private javax.swing.JLabel outputLabel;
    private static javax.swing.JTextArea outputTextArea;
    private javax.swing.JTextField pagesTextField;
    private javax.swing.JButton pasteButton;
    private javax.swing.JButton prevButton;
    private com.meraklisina.latexeditor.PreviewPanel previewPanel1;
    private javax.swing.JButton saveButton;
    public static javax.swing.JTabbedPane tab_Editors;
    private javax.swing.JPopupMenu toolbarContextMenu;
    private javax.swing.JPanel toolbarPanel;
    private javax.swing.JButton underlineButton;
    
    private JFrame completeMenu = new JFrame("AutoCompleteMenu");
    private AutoComplete autoComplete;
    
    JLabel label = new JLabel();
    // End of variables declaration//GEN-END:variables
}
